import { getYaliUserInfo } from '../../../utils/checkAuth';
import apiLiveList from '../../../yali-sdk/business/live/api/apiAnchorLives';
import { SUCCESS } from '../../../yali-sdk/utils/success';
import frequentClick from '../../../yali-sdk/utils/frequentClick';
import getIn from '../../../yali-sdk/utils/getIn';
import { addNotifier, notify, removeNotifier } from '../../../yali-sdk/utils/NotifyRegistryCenter';
import formattingDate from '../../../yali-sdk/utils/formattingDate';
import _list from '../../../yali-sdk/utils/list';
import { filterImg } from '../../imgBaseUrl';
import apiLiveShop from '../../../yali-sdk/business/live/api/apiAnchorLiveShops';
import initYaLiWebSocket from '../../../yali-sdk/utils/initYaLiWebSocket';
// 主播列表
Page({
    data: {
        page: 1,
        rows: 10,
        menuItems: [{ name: '店铺', id: -1 }],
        list: [],
        keywords: undefined,
        uid: undefined,
        web_id:undefined,
        productRows:5,
        status: undefined,
        pureAudio: false,
        menus: [{ current: 0, list: [{ title: '店铺', type: -1 }] }, { current: 0, list: [{ title: '全部状态',liveing:0}, { title: '未开始', type: 0,liveing:0 }, { title: '进行中', type: 1, liveing:1},{ title: '直播中', type: 1, liveing:2 }, { title: '已结束', type: 2,liveing:0 }] }],
    },
    onLoad() {
        this.liveList = new _list((params, cb) => global.actionDispatcher.execute(apiLiveList,params, cb), (core) => {
            const isLoaded = core.getIsLoaded();
            const isLoading = core.getIsLoading();
            const hasNext = core.getHasNext();
            const list = core.getScrollList();
            if (isLoaded) {
                wx.stopPullDownRefresh();
            }
            this.setData({ list, isLoaded, isLoading, hasNext });
        }, { filter: list => list && list.map(it => it
                .set('_end_time', formattingDate('yy/MM/dd hh:mm', new Date(it.get('end_time') * 1000)))
                .set('_start_time', formattingDate('yy/MM/dd hh: mm', new Date(it.get('start_time') * 1000)))
                .update('shop_logo', v => filterImg({ v }, 'v').v)
                    .updateIn(['products', 'list'], list => list && list.map(it => filterImg(it, 'pic')))) });
        addNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        addNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);
        addNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);// 修改价格
        initYaLiWebSocket();
    },
    onUnload() {
        removeNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        removeNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);
        removeNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);
    },
    // 更新活动状态
    refreshStatus(params) {
        if (params && params.liveId && params.status !== undefined) {
            const list = this.data.list && this.data.list.map((it) => {
                if (it.get('id') === params.liveId) {
                    return it.set('status', params.status).set('current_room', params.roomId);
                }
                return it;
            });
            this.setData({ list });
        }
    },
    // 更新活动当前推荐产品
    refreshCurrentProduct(params) {
        if (params && params.liveId && params.productId !== undefined) {
            const list = this.data.list && this.data.list.map((it) => {
                if (it.get('id') === params.liveId) {
                    return it.set('current_product', params.productId);
                }
                return it;
            });
            this.setData({ list });
        }
    },
    // 更新产品价格
    refreshProductPrice(params) {
        if (params && params.unitPrice !== undefined && params.productId !== undefined) {

            const list = this.data.list && this.data.list.map(it => it.updateIn(['products', 'list'], list => list && list.map((i) => {
                if (i.get('id') === params.productId) {
                    i = i.set('unit_price', params.unitPrice);
                }
                return i;
            })));
            this.setData({ list });
        }
    },
    onReady() {
        getYaliUserInfo().then((user) => {
            this.setData({ anchorId: user.id }, () => {
                this.onLoadLives();
                this.onLoadShop();
            });
        }, () => {
            //为应付审核，短暂这样设置
            // wx.showModal({
            //     content: '请先登录或注册主播',
            //     confirmText: '注册',
            //     cancelText:'登录',
            //     success(res) {
            //         if (res.confirm) {
            //             wx.navigateTo({ url: '/pages/regist/regist' });
            //         }else if (res.cancel) {
            //            wx.navigateTo({ url: '/pages/login/login' });
            //       }
            //     },
            // });
             wx.navigateTo({ url: '/pages/login/login' });
        });
    },
    onPullDownRefresh() {
        if (this.data.isLoading) return;
        this.onLoadLives();
    },
    onReachBottom() {
        if (this.data.isLoading || !this.data.hasNext) return;
        this.liveList.loadMore();
    },
    onLoadLives(item = {uid: this.data.uid,status: this.data.status, liveing: this.data.liveing, keywords:this.data.keywords, page: this.data.page, rows: this.data.rows, web_id: this.data.web_id }) {
        //console.log(item,'ffff奋斗到多多多多多多多多多多')
        this.liveList.loadNew({
            anchorId: this.data.anchorId,
            isProduct: true,
            web_id: item.web_id,
            keywords: item.keywords,
            status: item.status,
            liveing: item.liveing,
            uid: item.uid,
            productRows:5,
            page: item.page,
            rows: item.rows,
            orderType: 4,
        });
    },
    // 加载主播所有活动的店铺列表
    onLoadShop() {
        global.actionDispatcher.execute(apiLiveShop, {
            anchorId: this.data.anchorId,
        }, (f, fs) => {
            if (f === SUCCESS) {
                const list = getIn(fs, ['data']) && getIn(fs, ['data']).map(it => ({ ...it, title: it.shop_name }));
                this.data.menus[0] = { current: 0, list: [{ title: '店铺' }, ...list] };
                this.setData({ menus: this.data.menus });
            }
        });
    },
    // 搜索条的事件响应
    searchBarEvent(e) {
        if (e.detail && e.detail.type === 'click') {
            let current = getIn(e.detail.items, [1, 'current']);
            const status = getIn(e.detail.items, [1, 'list', current, 'type']); // 状态
            const liveing = getIn(e.detail.items, [1, 'list', current, 'liveing']);    
            const web_id = getIn(e.detail.items, [0, 'web_id']);    
            const page =this.data.page;
            const rows =this.data.rows;
            current = getIn(e.detail.items, [0, 'current']);
            const uid = getIn(e.detail.items, [0, 'list', current, 'uid']); // 店铺id
            this.onLoadLives({uid,status,liveing, web_id,page,rows});
        } else if (e.detail && e.detail.type === 'input') {
            const page =this.data.page;
            const rows =this.data.rows;
            this.onLoadLives({liveing:0,keywords: e.detail.keywords,page,rows});
        }
    },
    onDetail(e) {
        frequentClick().then(() => {
            const idx = getIn(e, ['currentTarget', 'dataset', 'idx']);
            wx.navigateTo({
                url: `/pages/anchor/detail/detail?item=${JSON.stringify(this.data.list.getIn([idx]).toJS())}`,
            });
        });
    },
});
